package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.ManagerUserMapper;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.QueryPageBean;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.ManagerRoleService;
import com.itheima.service.ManagerUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version V1.0
 * @author: TXT
 * @date: 2020/2/11 21:21
 * @description:
 */
@Service(interfaceClass = ManagerUserService.class)
@Transactional
public class ManagerUserServiceImpl implements ManagerUserService {

    @Autowired
    private ManagerUserMapper managerUserMapper;
    @Autowired
    private ManagerRoleServiceImpl managerRoleService;
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Page page = PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        List<User> allUser = managerUserMapper.findAllUser();
        return new PageResult(page.getTotal(),allUser);
    }

    @Override
    public void addUser(User user) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(user.getPassword());
        user.setPassword(encode);
        managerUserMapper.addUser(user);
        //在角色和用户关系表中维护关系
        managerUserMapper.addRoleUserByUserId(user);
    }

    @Override
    public Map findUserById(Integer id) {
        //查询用户信息
        User user = managerUserMapper.findUserById(id);
        // 查询所有角色
        List<Role> Roles = managerRoleService.findAll();
        //查询用户对应的角色
        List<Integer> roleIds = managerUserMapper.findRoleIdsByUserId(user.getId());
        Map map = new HashMap<>();
        map.put("user",user);
        map.put("Roles",Roles);
        map.put("roleIds",roleIds);
        return map;
    }

    @Override
    public void editUser(User user) {
        //修改用户信息
        managerUserMapper.updateUser(user);
        //修该户角色表 先删除在新增
        //删除用户对应的角色信息
        managerUserMapper.deleteUserAndRole(user.getId());
        //新增
        managerUserMapper.addRoleUserByUserId(user);
    }

    @Override
    public void deleteUser(Integer id) {
        //删除用户对应的角色信息
        managerUserMapper.deleteUserAndRole(id);
        //删除用户
        managerUserMapper.deleteUser(id);
    }
}
